// import MarkdownIt from 'markdown-it'
import MdEditor from 'react-markdown-editor-lite';
// 导入编辑器的样式
import ReactMarkdown from 'react-markdown';
import 'react-markdown-editor-lite/lib/index.css';
import rehypeKatex from 'rehype-katex';
import remarkGfm from 'remark-gfm'; // 引入remark-gfm插件来支持GitHub Flavored Markdown语法
import remarkMath from 'remark-math';

import './index.less';

import BreadCrumb from '@/components/BreadCrumb';
import { ftCreate, ftUpdate } from '@/service/modules/blogs';
import { ftUpload2 } from '@/service/modules/normon';
import { Itag } from '@/service/modules/tag';
import { getLocalStorage } from '@/utils/local';
import { CopyOutlined, PlusOutlined } from '@ant-design/icons';
import type { GetProp, UploadFile, UploadProps } from 'antd';
import { Button, Card, Form, Image, Input, message, Select, Upload } from 'antd';
import { memo, useEffect, useState } from 'react';
import rehypeRaw from 'rehype-raw'; //解析为HTML标签的插件
import { useLocation, useModel, useNavigate } from 'umi';

type FormValues = {
  id?: string;
  title: string;
  content: number;
  tagId: string;
  hotNum: number;
  commentNum: number;
  description: string;
};
type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

// 扩展 UploadFile 类型
interface ExtendedUploadFile extends UploadFile {
  originUrl?: string;
}

const getBase64 = (file: FileType): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });

const BlogsAddOrUpdatePage: React.FC = () => {
  const location = useLocation();
  const { detailAction, updateAction, selectAction } = useModel('blogsModel');
  const navigate = useNavigate();

  // md逻辑
  const [editorValue, setEditorValue] = useState('');
  function handleEditorChange(event: any) {
    setEditorValue(event.text);
  }
  function handleImageUpload(params: any): Promise<any> {
    return new Promise((resolve) => {
      resolve({
        url: 'https://avatars.githubusercontent.com/u/10656202?s=200&v=4',
      });
    });
  }

  const [form] = Form.useForm<FormValues>();
  const [id, setId] = useState<string>();
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [fileList, setFileList] = useState<ExtendedUploadFile[]>([
    // {
    //   uid: '-1',
    //   name: 'image.png',
    //   status: 'done',
    //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    // },
  ]);
  const [tagOptions, setTagOptions] = useState<Itag[]>([]);
  // 预览
  const handlePreview = async (file: ExtendedUploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as FileType);
    }

    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
  };
  // 修改上传
  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) =>{
    console.log(newFileList);
    setFileList(newFileList);
  }

  // 下载样式
  const uploadButton = (
    <button style={{ border: 0, background: 'none' }} type="button">
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>Upload</div>
    </button>
  );

  // 复制
  const handleCopyUrl = (url: string | any) => {
    navigator.clipboard
      .writeText(url)
      .then(() => {
        message.success('链接已复制到剪贴板');
      })
      .catch((error) => {
        message.error('复制失败: ' + error);
      });
  };

  // 保存
  function onSave() {
    form.validateFields().then((values) => {
      const params = {
        id: id || undefined,
        tagId: values.tagId?.toString() || '',
        title: values.title,
        content: editorValue,
        imageList: fileList
          .map((item) => {
            if (item.originUrl) {
              return item.originUrl;
            } else {
              const { url } = item.response.data;
              return url;
            }
          })
          .toString(),
          hotNum: values.hotNum || 0,
          commentNum: values.commentNum || 0,
          description: values.description,
      };
      if (id) {
        ftUpdate(params).then((res) => {
          if (res.code === 200) {
            message.success('保存成功');
            navigate(`/blogsmanage/index`, { replace: true });
          } else {
            message.error('保存失败');
          }
        });
      } else {
        ftCreate(params).then((res) => {
          if (res.code === 200) {
            message.success('保存成功');
            navigate(`/blogsmanage/index`, { replace: true });
          } else {
            message.error('保存失败');
          }
        });
      }
    });
  }

  // 回显
  useEffect(() => {
    if (location.state) {
      const { id = undefined } = location.state as any;
      setId(id);
      if (!id) return;
      detailAction(id).then((res) => {
        const { code, data, message } = res;
        const { id, content, title, tag_id, imageList,hotNum,commentNum, description } = data;
        form.setFieldsValue({
          id,
          title,
          tagId: tag_id && tag_id.split(','),
          hotNum: hotNum || 0,
          commentNum: commentNum || 0,
          description
        });
        setEditorValue(content || '');
        setFileList(
          (imageList &&
            imageList.split(',').map((item: string) => {
              return {
                uid: item,
                name: item,
                status: 'done',
                url: `${process.env.UMI_APP_API_URL}${item}`,
                originUrl: item,
              };
            })) ||
            [],
        );
      });
    }
    selectAction().then((res) => {
      console.log(res);
      setTagOptions(
        res.data?.map((item: Itag) => ({
          id: item.id,
          text: item.text,
          createTime: item.createTime ?? '', // 若无该字段可设默认值
          updateTime: item.updateTime ?? '', // 若无该字段可设默认值
        })) || [],
      );
    });
  }, []);

  return (
    <>
      <BreadCrumb />
      <br />
      <Card title={'基本信息'} variant="borderless" style={{ margin: '20px 0' }}>
        <Form form={form} name="demo_form" layout="horizontal" labelCol={{ span: 3 }}>
          <Form.Item label="标题" name="title" rules={[{ required: true, message: '请输入标题!' }]}>
            <Input placeholder="请输入标题" style={{ width: 360 }} />
          </Form.Item>
          <Form.Item label="类型" name="tagId">
            <Select mode="multiple" placeholder="请选择" style={{ width: 360 }}>
              {tagOptions.map((item) => {
                return <Select.Option value={item.id}>{item.text}</Select.Option>;
              })}
            </Select>
          </Form.Item>
          <Form.Item label="图片链接" name="imageList">
            <Upload
              action={ftUpload2}
              headers={{ Authorization: `Bearer ${getLocalStorage('token')}` }}
              listType="picture-card"
              fileList={fileList}
              onPreview={handlePreview}
              onChange={handleChange}
              itemRender={(originNode, file) => (
                <div className="custom-upload-item">
                  {originNode}
                  {(
                    <CopyOutlined
                      className="copy-icon"
                      onClick={(e) => {
                        e.stopPropagation(); // 防止触发其他事件
                        handleCopyUrl(file.url ? file.url! : `${process.env.UMI_APP_API_URL}${file.response.data.url}` );
                      }}
                    />
                  )}
                </div>
              )}
            >
              {uploadButton}
            </Upload>
            {previewImage && (
              <Image
                wrapperStyle={{ display: 'none' }}
                preview={{
                  visible: previewOpen,
                  onVisibleChange: (visible) => setPreviewOpen(visible),
                  afterOpenChange: (visible) => !visible && setPreviewImage(''),
                }}
                src={previewImage}
              />
            )}
          </Form.Item>
          <Form.Item label="热度数" name="hotNum" >
            <Input type='number' placeholder="请输入热度数" style={{ width: 360 }} defaultValue={0} />
          </Form.Item>
          <Form.Item label="评论数(暂用)" name="commentNum">
            <Input type='number' placeholder="请输入评论数" style={{ width: 360 }} defaultValue={0} />
          </Form.Item>
          <Form.Item label="描述" name="description" rules={[{ required: true, message: '请输入描述!' }]}>
            <Input.TextArea placeholder="请输入描述"  />
          </Form.Item>
        </Form>
      </Card>

      <Card title={'博客内容'} variant="borderless" style={{ margin: '20px 0' }}>
        <MdEditor
          className="markdown-editor"
          renderHTML={(text) => {
            return (
              <ReactMarkdown
                remarkPlugins={[
                  remarkGfm,
                  [remarkMath, { singleTilde: false }], // 注意这里要传递对象参数
                ]}
                rehypePlugins={[rehypeRaw, [rehypeKatex, { output: 'html' }]]}
              >
                {text}
              </ReactMarkdown>
            );
          }}
          value={editorValue}
          onChange={({ html, text }) => {
            handleEditorChange({ html, text });
          }}
          onCustomImageUpload={handleImageUpload}
        ></MdEditor>
      </Card>
      <div className="btn-btm">
        <Button type="primary" onClick={onSave}>
          保存
        </Button>
      </div>
    </>
  );
};

export default memo(BlogsAddOrUpdatePage);
